//
//  LineEffect.cpp
//  client
//
//  Created by will on 17/07/2017.
//
//

#include "LineEffect.hpp"



LineEffect* LineEffect::create(const std::string& filename,EffectStretchMode mode)
{
    auto ret = new (std::nothrow) LineEffect();
    bool ok = ok = ret->init(filename,mode);

    if(ok)
    {
        return ret;
    }
    CC_SAFE_DELETE(ret);
    return nullptr;
}

bool LineEffect::init(const std::string& filename,EffectStretchMode mode)
{
    bool ok = false;
    
    _stretchMode = mode;

    if(filename.empty())
    {
        ok = Sprite::init();
    }
    else
    {
        ok = Sprite::initWithFile(filename);
    }
    
    _originTexRect = getTextureRect();
    
    
    return ok;
}

LineEffect::LineEffect()
:_stretchMode(EffectStretchMode::SCALING)
{
    
    
}

LineEffect::~LineEffect()
{
    
}


void LineEffect::setSpriteFrame(SpriteFrame* newFrame)
{
    Sprite::setSpriteFrame(newFrame);
    _originTexRect = getTextureRect();
    if(_stretchMode==EffectStretchMode::TILED)
    {
        enableTextureRepeated(true);
    }
    updateLinkPos();
}

void LineEffect::setTexture(Texture2D *texture)
{
    Sprite::setTexture(texture);
    if(_stretchMode==EffectStretchMode::TILED)
    {
        enableTextureRepeated(true);
    }
}

void LineEffect::updateLinkPos(){
    Vec2 mid= (_start+_end) *0.5 ;
    Vec2 dir=(_end-_start).getNormalized();
    float A;
    if(dir.y<=0){
        A=acosf(dir.x)*180/M_PI;
    }else{
        A=(2*M_PI-acosf(dir.x))*180/M_PI;
    }
    this->setPosition(mid);
    this->setRotation(A);
    
    float targetLen=_start.distance(_end);
    if(_stretchMode==EffectStretchMode::TILED)
    {
        _originTexRect.size.width = targetLen;
        setTextureRect(_originTexRect);
    }
    else
    {
        float originWidth = getContentSize().width;
        float s = targetLen/originWidth;
        setScaleX(s);
    }
}

void LineEffect::setStartPos(const Vec2&start){
    _start=start;
    updateLinkPos();
}

void LineEffect::setEndPos(const Vec2&end){
    _end=end;
    updateLinkPos();
}

